package club.ljwang.security;

import club.ljwang.pojo.Permission;
import club.ljwang.pojo.Role;
import club.ljwang.pojo.User;
import club.ljwang.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Auther: wangl
 * @Date: 2020/3/7 17:39
 * @Description:
 */

//这里需要调用Dubbo服务查询用户的权限,所以用使用Dubbo的扫描
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.findByUserName(username);

        if (user == null) {
            return null;
        }
        //2、查询用户的权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {

                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));

            }

        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}
